package org.jeecg.modules.bigscreen.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.behavior.service.ILwgyBehaviorService;
import org.jeecg.modules.basic.demo.apartment.service.ILwgyBaseApartmentService;
import org.jeecg.modules.basic.demo.bed.entity.LwgyBaseBed;
import org.jeecg.modules.basic.demo.bed.service.ILwgyBaseBedService;
import org.jeecg.modules.basic.demo.school.entity.LwgyBaseSchool;
import org.jeecg.modules.basic.demo.school.service.ILwgyBaseSchoolService;
import org.jeecg.modules.basic.demo.student.entity.LwgyBaseStudent;
import org.jeecg.modules.basic.demo.student.service.ILwgyBaseStudentService;
import org.jeecg.modules.basic.entry.entity.Apartment;
import org.jeecg.modules.basic.entry.service.impl.LwgyInoutRecordServiceImpl;
import org.jeecg.modules.basic.repair.service.ILwgyRepairMaintenanceService;
import org.jeecg.modules.sanitation2.entity.StatisticalDTO;
import org.jeecg.modules.sanitation2.mapper.LwgyScoreSanitationMapper1;
import org.jeecg.modules.sanitation2.service.ILwgyScoreSanitationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Description: 数据大屏
 * @Author: zhangjiaping
 * @Date: 2021-05-18
 * @Version: V1.0
 */
@Service
@Slf4j
public class BigScreenService {

    @Autowired
    private ILwgyBaseBedService iLwgyBaseBedService;

    @Autowired
    private ILwgyBaseStudentService iLwgyBaseStudentService;

    @Autowired
    private ILwgyBaseApartmentService iLwgyBaseApartmentService;

/*    @Autowired
    private ILwgyElecRecordService lwgyElecRecordService;*/

    @Autowired
    private ILwgyScoreSanitationService lwgyScoreSanitationService;

    @Autowired
    private ILwgyBaseSchoolService lwgyBaseSchoolService;

    @Autowired
    private ILwgyBehaviorService lwgyBehaviorService;

    @Autowired
    private LwgyInoutRecordServiceImpl lwgyInoutRecordService;

    @Autowired
    private LwgyScoreSanitationMapper1 lwgyScoreSanitationMapper1;

    @Autowired
    private ILwgyRepairMaintenanceService lwgyRepairMaintenanceService;


    public Map<String, Object> getHotelData() {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> role = iLwgyBaseBedService.getRoleById(sysUser.getId());

        long totalStart = System.currentTimeMillis();
        Map<String, Object> result = new HashMap<>(16);
        //初始数据
        result.put("totalBeds", 0);
        result.put("usedBeds", 0);
        result.put("unUsedBeds", 0);
        result.put("boyAllBeds", 0);
        result.put("girlAllBeds", 0);
        result.put("boyBeds", 0);
        result.put("girlBeds", 0);
        result.put("tmpBeds", 0);
        //获取总床位数据
        long start1 = System.currentTimeMillis();
        QueryWrapper<LwgyBaseBed> queryWrapper = new QueryWrapper<>();
        //queryWrapper.select("student_id","id","room_id");
        if(role.contains("fdy")){
            String workNo = sysUser.getWorkNo();
            queryWrapper.eq("admin_id",workNo);
        }
        queryWrapper.eq("del_flag",0);
        queryWrapper.eq("room_type","hotel_room");
        List<LwgyBaseBed> list = iLwgyBaseBedService.getHotelData(queryWrapper);
        long end1 = System.currentTimeMillis();
        log.info("bedList  耗时："+(end1-start1));
        if (list != null) {

            //总床位数
            result.put("totalBeds", list.size());
            //已住床位数
            List<LwgyBaseBed> listT = list.stream().filter(item -> { return (StringUtils.isNotEmpty(item.getStudentId())
                    && !StringUtils.equals(item.getStudentId(),"null"));}).collect(Collectors.toList());
            List<LwgyBaseBed> listB = list.stream().filter(item -> { return StringUtils.equals(item.getRoomSex(),"1");
            }).collect(Collectors.toList());
            List<LwgyBaseBed> listG = list.stream().filter(item -> { return StringUtils.equals(item.getRoomSex(),"2");
            }).collect(Collectors.toList());
            if (listT != null) {
                result.put("usedBeds", listT.size());
                result.put("unUsedBeds", list.size() - listT.size());
                result.put("boyAllBeds", listB.size());
                result.put("girlAllBeds", listG.size());
                //处理男女生的数量
                List<String> ids = new ArrayList<>(listT.size());
                listT.stream().forEach(item -> {
                    ids.add(item.getStudentId());
                });
                long start = System.currentTimeMillis();
                List<LwgyBaseStudent> studentList = iLwgyBaseStudentService
                        .list(Wrappers.<LwgyBaseStudent>lambdaQuery()
                                .select(LwgyBaseStudent::getStudentSex,LwgyBaseStudent::getId)
                                .in(LwgyBaseStudent::getId, ids));
               /* QueryWrapper<LwgyBaseStudent> studentQueryWrapper = new QueryWrapper<>();
                studentQueryWrapper.select("student_sex","id");
                long startQueryStu = System.currentTimeMillis();
                List<LwgyBaseStudent> studentList = iLwgyBaseStudentService.list(studentQueryWrapper);
                long endQueryStu = System.currentTimeMillis();
                log.info("query studentList 耗时："+(endQueryStu-startQueryStu));

                studentList = studentList.parallelStream().filter(student->ids.contains(student.getId())).collect(Collectors.toList());*/
                long end = System.currentTimeMillis();
                log.info("studentList filter 耗时："+(end-start));
                AtomicInteger boy = new AtomicInteger();
                AtomicInteger girl = new AtomicInteger();
                studentList.stream().forEach(item -> {
                    if ("1".equals(item.getStudentSex())) {
                        boy.getAndIncrement();
                    } else if ("2".equals(item.getStudentSex())) {
                        girl.getAndIncrement();
                    }
                });
                result.put("boyBeds", boy.intValue());
                result.put("girlBeds", girl.intValue());
                //各楼宇住宿情况
//                List<Map<String, Object>> dataList = new ArrayList<>(16);
              /*  long start2 = System.currentTimeMillis();
                Wrappers.<LwgyBaseApartment>lambdaQuery().eq(LwgyBaseApartment::getType, "building");
                QueryWrapper<LwgyBaseApartment> apartmentQueryWrapper = new QueryWrapper<>();
                apartmentQueryWrapper.select("id","name","inner_code");
                apartmentQueryWrapper.eq("type","building");
                List<LwgyBaseApartment> apartmentList = iLwgyBaseApartmentService.list(apartmentQueryWrapper);
                long end2 = System.currentTimeMillis();
                log.info("apartmentList lambdaQuery 耗时："+(end2-start2));
                List<Map<String, Object>>dataList = new ArrayList<>();
                if (apartmentList != null) {
                    List<String> finalIds = new ArrayList<>(listT.size());
                    listT.stream().forEach(item -> {
                        finalIds.add(item.getRoomId());
                    });
                    Map<String, Object> map;
                    long startLoop = System.currentTimeMillis();
                    for (LwgyBaseApartment apartment : apartmentList) {
                        map = new HashMap<>(apartmentList.size());
                        map.put("name", apartment.getName());
                        //计算每个楼宇入住人数
                        //List<LwgyBaseApartment> apartmentListT = iLwgyBaseApartmentService.list(Wrappers.<LwgyBaseApartment>lambdaQuery().like(LwgyBaseApartment::getInnerCode, apartment.getInnerCode()).in(LwgyBaseApartment::getId, finalIds));
                        apartmentQueryWrapper = new QueryWrapper<>();
                        apartmentQueryWrapper.select("id");
                        apartmentQueryWrapper.like("inner_code",apartment.getInnerCode());
                        List<LwgyBaseApartment> apartmentListT = iLwgyBaseApartmentService.list(apartmentQueryWrapper);
//                        .in(LwgyBaseApartment::getId, finalIds)
                        apartmentListT = apartmentListT.parallelStream().filter(item->finalIds.contains(item.getId())).collect(Collectors.toList());
                        map.put("value", apartmentListT.size());
                        dataList.add(map);
                    }
                    dataList.forEach(System.out::println);
                }*/
                List<Map<String,Object>> dataList1;
                if(role.contains("fdy")){
                    String workNo = sysUser.getWorkNo();
                    dataList1 = iLwgyBaseApartmentService.getEveryBuildPersonNumBer(workNo);
                } else {
                    dataList1 = iLwgyBaseApartmentService.getEveryBuildPersonNumBerS();
                }
//                String workNo = sysUser.getWorkNo();
//                List<Map<String,Object>> dataList1 = iLwgyBaseApartmentService.getEveryBuildPersonNumBer(workNo);
               /* List<LwgyRoomStatistics> dataList = iLwgyBaseApartmentService.getEveryBuildPersonNumBer();
                Map<String, Integer> collect = dataList.stream().collect(Collectors.toMap(LwgyRoomStatistics::getBuildingName, LwgyRoomStatistics::getPersonNum));
                List<Map<String, Object>> maps = new ArrayList<>(collect.size());
                collect.forEach((key,value)->{
                    HashMap<String, Object> stringIntegerHashMap = new HashMap<>();
                    stringIntegerHashMap.put(key,value);
                    maps.add(stringIntegerHashMap);
                });
//                maps.add(collect);
                maps.forEach(System.out::println);*/
//                dataList1.forEach(System.out::println);
                result.put("ranking", dataList1);
            } else {
                result.put("unUsedBeds", list.size());
            }
        }
        long totalEnd = System.currentTimeMillis();
        log.info("总耗时："+(totalEnd-totalStart));
        return result;
    }


/*    public List<String[]> getBuildingElectricityData() {
        //iLwgyBaseApartmentService
        String[] electricity;
        List<String[]> strings = new LinkedList<>();
        List<LwgyElecRecord> lwgyElecRecords = lwgyElecRecordService.buildElectricityData();
        for (LwgyElecRecord lwgyElecRecord : lwgyElecRecords) {
            electricity = new String[]{lwgyElecRecord.getBuilding(),"110", "<span class='colorGrass'>↑75</span>"};
            strings.add(electricity);
        }
        return strings;
    }*/

    public  List<Object[]> getCheckScore() {
        List<Object[]> strings = new LinkedList<>();
        /*
        List<LwgyBaseApartment> building = iLwgyBaseApartmentService.list(Wrappers.<LwgyBaseApartment>lambdaQuery()
                .select(LwgyBaseApartment::getName)
                .eq(LwgyBaseApartment::getType, "building"));
        ArrayList<String> apartmentList = new ArrayList<>(building.size());
        for (LwgyBaseApartment lwgyBaseApartment : building) {
            apartmentList.add(lwgyBaseApartment.getName());
        }
        */
        List<StatisticalDTO> list = lwgyScoreSanitationService.getStatistical();
        ArrayList<String> apartments = new ArrayList<>(list.size());
        ArrayList<Integer> qualifieds = new ArrayList<>(list.size());
        ArrayList<Integer> unqualifieds = new ArrayList<>(list.size());
        /*list.stream()
                .filter(statisticalDTO ->
                        statisticalDTO.getQualified()+statisticalDTO.getUnqualified()>0)
                .forEach(statisticalDTO -> qualifieds.add(statisticalDTO.getQualified()));
        list.stream()
                .filter(statisticalDTO ->
                        statisticalDTO.getQualified()+statisticalDTO.getUnqualified()>0)
                .forEach(statisticalDTO -> unqualifieds.add(statisticalDTO.getUnqualified()));
        list.stream()
                .filter(statisticalDTO ->
                        statisticalDTO.getQualified()+statisticalDTO.getUnqualified()>0)
                .forEach(statisticalDTO -> apartments.add(statisticalDTO.getName()));*/
        for (StatisticalDTO statisticalDTO : list) {
            Integer qualified = statisticalDTO.getQualified();
            Integer unqualified = statisticalDTO.getUnqualified();
            if(qualified+unqualified>0){
                apartments.add(statisticalDTO.getName());
                qualifieds.add(qualified);
                unqualifieds.add(unqualified);
            }
        }
        String[] apartment = new String[apartments.size()];
        apartment = apartments.toArray(apartment);
        strings.add(apartment);

        Integer[] qualified = new Integer[qualifieds.size()];
        qualified = qualifieds.toArray(qualified);
        strings.add(qualified);

        Integer[] unqualified = new Integer[unqualifieds.size()];
        unqualified = unqualifieds.toArray(unqualified);
        strings.add(unqualified);

        return strings;
    }

    public List<Map<String, Integer>> queryCollegeViolationInfo(String selectedSchools) {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        String schoolYear = "";
        if (month > 8) {
            schoolYear = String.valueOf(year) + "-" +String.valueOf(year + 1);
        } else {
            schoolYear = String.valueOf(year-1) + "-" +String.valueOf(year);
        }
        String id = lwgyScoreSanitationMapper1.getNewId();// 7
        if (oConvertUtils.isEmpty(selectedSchools)) {
            return null;
        }
        String[] fields = selectedSchools.split(",");// A01

        QueryWrapper<LwgyBaseSchool> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","name");
        queryWrapper.in("sys_org_code",Arrays.asList(fields));
        queryWrapper.eq("university_sort","campus");
        List<LwgyBaseSchool> schoolList = lwgyBaseSchoolService.getBaseMapper().selectList(queryWrapper);
        for (LwgyBaseSchool school : schoolList) {
            school.setSchoolYear(schoolYear);
            school.setScaleBatches(id);
        }
        if(oConvertUtils.listIsEmpty(schoolList)){
            return null;
        }
       return lwgyBehaviorService.queryCollegeViolationInfo(schoolList);

    }


    public List<String[]> queryHealthScore() {
        String weeks = lwgyScoreSanitationMapper1.getNewWeeks();
        return lwgyScoreSanitationService.queryHealthScoreInfo(weeks);
    }

    public List<Apartment> queryPowerData(String xq,String lh,String fjh,String state,String count) { ;
        List<Apartment> list =  lwgyInoutRecordService.selectList(xq,lh,fjh,state,count);
        return list;
    }

    public List<Map<String,Object>> roomShutOff() { ;
        List<Map<String,Object>> list =  lwgyInoutRecordService.roomShutOff();
        return list;
    }

    public List<Map<String,Object>> queryRepairData() { ;
        List<Map<String,Object>> list =  lwgyRepairMaintenanceService.queryRepairData();
        return list;
    }
}
